package com.corpgovernment.organization.service.impl;

import com.corpgovernment.common.enums.PhoneCountryCodeEnum;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.entity.SyncOrganizationRequestEntity;
import com.corpgovernment.organization.entity.db.MbImportExcelRecordDetailLog;
import com.corpgovernment.organization.enumm.OrgInfoSheetEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.enumm.ServiceErrorEnum;
import com.corpgovernment.organization.util.StrUtils;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;

@Slf4j
@Service
public class CheckSyncOrgService {

    public ServiceErrorEnum checkOrganizationRequest(SyncOrganizationRequestEntity.SyncOrganizationInfoEntity org,List<MbImportExcelRecordDetailLog> inValidList) {
        // 空值判断
        if (org == null) {
            log.error("checkOrganizationRequest org 空值判断");

            inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyOrgInfo_Failure,org.getLineNo(),org.getLineNo()));
            return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyOrgInfo_Failure;
        }
        // 默认不删除
        org.setIsDelete(Optional.ofNullable(org.getIsDelete()).orElse(false));

        // 空值判断
        if (org.getBasicInfo() == null
                || StringUtils.isEmpty(org.getBasicInfo().getName())
                || StringUtils.isEmpty(org.getBasicInfo().getType())) {
            log.error("checkOrganizationRequest org.getBasicInfo() 空值判断");

            inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyBasicInfo_Failure,org.getLineNo(),org.getLineNo()));
            return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyBasicInfo_Failure;
        }
        // 超出赋值范围
        if (!StrUtils.In(org.getBasicInfo().getType(), OrgTypeEnum.C.getCode(), OrgTypeEnum.D.getCode())) {
            log.error("checkOrganizationRequest org.getBasicInfo().getType()为{} 超出赋值范围C或D", org.getBasicInfo().getType());
            inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_OutOfOrgType_Failure,org.getLineNo(),org.getLineNo()));
            return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_OutOfOrgType_Failure;
        }
        // 顶层组织，只能是公司
        if (OrgTypeEnum.D.getCode().equals(org.getBasicInfo().getType()) && StringUtils.isEmpty(org.getBasicInfo().getParentBusinessCode())) {
            log.error("checkOrganizationRequest 顶层组织，只能是公司");
            inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ErrorParentOrgId_Failure,org.getLineNo(),org.getLineNo()));
            return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ErrorParentOrgId_Failure;
        }
        // 默认成本中心不为空时，成本中心必须也不为空，且包含成本中心
        if(StringUtils.isNotBlank(org.getBasicInfo().getCostCenterInfoDefault())) {
            if(!org.getBasicInfo().getCostCenterInfoDefault().contains("/")) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_ERROR,org.getLineNo(),org.getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_ERROR;
            }
            if(org.getBasicInfo().getCostCenterInfoDefault().split("/").length != 2) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_More,org.getLineNo(),org.getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_More;
            }
            if(StringUtils.isBlank(org.getBasicInfo().getCostCenterInfo())) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure,org.getLineNo(),org.getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure;
            }
            Boolean flag = true;
            String[] costCenters = org.getBasicInfo().getCostCenterInfo().split(";");
            for (String costCenter : costCenters) {
               if(StringUtils.equals(org.getBasicInfo().getCostCenterInfoDefault(), costCenter, false)) {
                   flag = false;
               }
            }
            if(flag) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure,org.getLineNo(),org.getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_Cost_Center_Info_Default_Failure;
            }
        }
        // 默认有效
        org.getBasicInfo().setIsActive(Optional.ofNullable(org.getBasicInfo().getIsActive()).orElse(true));


        // 联系人信息判断
        if (org.getContactInfo() != null) {
            PhoneCountryCodeEnum phoneCountryCodeEnum = StringUtils.isEmpty(org.getContactInfo().getContactCountryCode()) ? PhoneCountryCodeEnum.CN : PhoneCountryCodeEnum.getByCountryCode(org.getContactInfo().getContactCountryCode());
            if (phoneCountryCodeEnum == null) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_CountryCodeFormat_Failure,org.getLineNo(),org.getContactInfo().getLineNo()));
                return  ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_CountryCodeFormat_Failure;
            }
            if (!StringUtils.isEmpty(org.getContactInfo().getContactEmail()) && !org.getContactInfo().getContactEmail().matches("^[A-Za-z0-9\\-_]+[A-Za-z0-9\\.\\-_]*[A-Za-z0-9\\-_]+@[A-Za-z0-9]+[A-Za-z0-9\\.\\-_]*(\\.[A-Za-z0-9\\.\\-_]+)*[A-Za-z0-9]+\\.[A-Za-z0-9]+[A-Za-z0-9\\.\\-_]*[A-Za-z0-9]+$")) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_EmailFormat_Failure,org.getLineNo(),org.getContactInfo().getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_EmailFormat_Failure;

            }
            Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
            if (!StringUtils.isEmpty(org.getContactInfo().getContactPhone()) && !p.matcher(org.getContactInfo().getContactPhone()).find()) {
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INFO,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_PhoneFormat_Failure,org.getLineNo(),org.getContactInfo().getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_ContactInfo_PhoneFormat_Failure;
            }
        }

        if (CollectionUtils.isNotEmpty(org.getInvoiceList())) {
            // 只有公司才能关联发票
            if (!OrgTypeEnum.C.getCode().equals(org.getBasicInfo().getType())) {
                log.error("checkOrganizationRequest 只有公司才能关联发票，删除发票");
                inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INVOICE,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_InvoiceButNotCompany_Failure,org.getLineNo(),org.getLineNo()));
                return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_InvoiceButNotCompany_Failure;
            }

            for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.InvoiceInfoEntity invoice : org.getInvoiceList()) {
                // 空值判断
                if (invoice != null && (StringUtils.isEmpty(invoice.getInvoiceTitle()) || StringUtils.isEmpty(invoice.getTaxId())
                        || StringUtils.isEmpty(invoice.getAccountBank()) || StringUtils.isEmpty(invoice.getAccountCardNo())
                        || StringUtils.isEmpty(invoice.getCorporationPhone()) || StringUtils.isEmpty(invoice.getCorporationAddress()))) {
                    log.error("checkOrganizationRequest org.getInvoiceTitle() 空值判断");
                    inValidList.add(buildErrorInfo(OrgInfoSheetEnum.INVOICE,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyInvoiceInfo_Failure,org.getLineNo(),invoice.getLineNo()));
                    return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyInvoiceInfo_Failure;
                }
            }
            // 去除null项
            org.getInvoiceList().removeIf(Objects::isNull);
        }

        if (CollectionUtils.isNotEmpty(org.getDeliveryAddressList())) {
            for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.DeliveryAddressEntity address : org.getDeliveryAddressList()) {
                // 空值判断
                if (address != null && (StringUtils.isEmpty(address.getProvinceName()) || StringUtils.isEmpty(address.getCityName())
                        || StringUtils.isEmpty(address.getDistrictName()) || StringUtils.isEmpty(address.getAddress())
                        || StringUtils.isEmpty(address.getRecipientName()) || StringUtils.isEmpty(address.getRecipientPhone()))) {
                    log.error("checkOrganizationRequest org.getDeliveryAddressList() 空值判断");
                    inValidList.add(buildErrorInfo(OrgInfoSheetEnum.DELIVERY,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyDeliveryInfo_Failure,org.getLineNo(),address.getLineNo()));
                    return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_EmptyDeliveryInfo_Failure;
                }
                if (address != null) {
                    // 默认不是默认配送地址
                    address.setIsDefault(Optional.ofNullable(address.getIsDefault()).orElse(false));
                    PhoneCountryCodeEnum phoneCountryCodeEnum = StringUtils.isEmpty(address.getRecipientCountryCode()) ? null : PhoneCountryCodeEnum.getByCountryCode(address.getRecipientCountryCode());
                    if (phoneCountryCodeEnum == null) {
                        // 默认中国大陆
                        address.setRecipientCountryCode(PhoneCountryCodeEnum.CN.getCountryCode());
                    }
                    if (!StringUtils.isEmpty(address.getPostCode()) && !address.getPostCode().matches("^[0-9]\\d{5}$")) {
                        inValidList.add(buildErrorInfo(OrgInfoSheetEnum.DELIVERY,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PostCodeFormat_Failure,org.getLineNo(),address.getLineNo()));
                        return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PostCodeFormat_Failure;
                    }
                    Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
                    if (!StringUtils.isEmpty(address.getRecipientPhone()) && !p.matcher(address.getRecipientPhone()).find()) {
                        inValidList.add(buildErrorInfo(OrgInfoSheetEnum.DELIVERY,ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PhoneFormat_Failure,org.getLineNo(),address.getLineNo()));
                        return ServiceErrorEnum.SyncHumanResources_SyncOrgInfo_DeliveryAddress_PhoneFormat_Failure;
                    }
                }
            }
            // 去除null项
            org.getDeliveryAddressList().removeIf(Objects::isNull);
        }


        if (CollectionUtils.isNotEmpty(org.getPostInfoList())) {
            for (SyncOrganizationRequestEntity.SyncOrganizationInfoEntity.PostInfoEntity postInfoEntity : org.getPostInfoList()) {
                if (StringUtils.isBlank(postInfoEntity.getName())) {
                    //inValidList.add(buildErrorInfo(OrgInfoSheetEnum.POST,ServiceErrorEnum.SyncHumanResources_SyncEmployeeInfo_PostInfo_Failure,org.getLineNo(),postInfoEntity.getLineNo()));
                    return ServiceErrorEnum.SyncHumanResources_SyncEmployeeInfo_PostInfo_Failure;
                }
            }
        }

        return ServiceErrorEnum.Success;
    }

    private MbImportExcelRecordDetailLog buildErrorInfo(OrgInfoSheetEnum orgInfoSheetEnum,ServiceErrorEnum serviceErrorEnum,String mainLineNo,String lineNo) {
        MbImportExcelRecordDetailLog mbImportExcelRecordDetailLog = new MbImportExcelRecordDetailLog();
        mbImportExcelRecordDetailLog.setLineNo(lineNo);
        mbImportExcelRecordDetailLog.setMainLineNo(mainLineNo);
        mbImportExcelRecordDetailLog.setMessage(serviceErrorEnum.getErrorMessage());
        mbImportExcelRecordDetailLog.setSheetIndex(orgInfoSheetEnum.getIndex());
        mbImportExcelRecordDetailLog.setSheetName(orgInfoSheetEnum.getName());
        mbImportExcelRecordDetailLog.setStatus("F");
        mbImportExcelRecordDetailLog.setDatachangeCreatetime(new Date());
        mbImportExcelRecordDetailLog.setDatachangeLasttime(new Date());
        return mbImportExcelRecordDetailLog;
    }
}
